﻿// 服务端，渲染生成环境
let express = require('express');
// websocket - express
let expressWs = require('express-ws');
let https = require('https');
let http = require('http');
// ejs模块
let ejs = require('ejs');
let path = require('path');
// 操作文件
let fs = require('fs');
let axios = require('axios')
const os = require('os');
// 接受表单文件
let formidable = require('formidable');
let app = express();

// token 加密接口
const jwt = require("jsonwebtoken");
const SECRET = "wen_xin_lin_key_secret";
// 视频通话token获取
let { getToken } = require('./public/video/token.js')

// SSL
let options = {
    key: fs.readFileSync('./ssl/qiaonan.info.key'),
    cert: fs.readFileSync('./ssl/qiaonan.info_bundle.crt')
}

let server = http.createServer(options, app)
// 配置wss
// let WSS = expressWs(app, server, {
//     wsOptions: {
//         options,//ssl
//     }
// });
let WSS = expressWs(app, server, {
    // wsOptions: {
    //     options,//ssl
    // }
});
// server.listen(8124, () => {
//     console.log('本机服务器地址：', 'https://localhost:8124', '或', `https://${getIpAddress()}:8124`)
// })
server.listen(8123, () => {
    console.log('本机服务器地址：', 'https://localhost:8123', '或', `https://${getIpAddress()}:8123`)
})

/* 
 const wsOptions = options.wsOptions || {};
  wsOptions.server = server;
  const wsServer = new ws.Server(wsOptions);
*/
// 使用 req.body
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


let mysql = require('mysql');
let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'chat',

    // 远程本地
    // host: '1.14.99.93',
    // user: 'local_chat',
    // password: 'y2SbkF4pdbRbeM3Z',
    // database: 'local_chat',

    // 编码
    charset: "utf8mb4",
    collate: "utf8mb4_unicode_ci",
    useConnectionPooling: true,
    port: 3306,//远程ip需要放行端口
})
connection.connect();

app.engine('html', ejs.__express)
// 静态资源
app.use(express.static(path.join(__dirname, 'upload')))
app.use(express.static(path.join(__dirname, 'dist')))
app.use(express.static(path.join(__dirname, 'src')))
// 解决跨域
app.use((req, res, next) => {
    //设置请求头
    res.set({
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Max-Age': 1728000,
        'Access-Control-Allow-Origin': req.headers.origin || '*',
        // 前端运行添加的header
        'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type,user-id,token',
        // 前端获取 设置的header
        'Access-Control-Expose-Headers': 'user-id,token',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
        'Content-Type': 'application/json; charset=utf-8'
    })
    req.method === 'OPTIONS' ? res.status(204).end() : next()
})
app.get('/', (req, res) => {
    res.render('../dist/index.html');
})
app.get('/123',(req,res) => {
    res.send('123')
})
// 获取视频第三方token
app.get('/get/token', (req, res) => {
    const { userId, username } = req.query || {}
    const token = getToken({
        appID: 839080308,
        serverSecret: '95debb6a778719428e871144be56e06f',
        userId: userId,
        effectiveTimeInSeconds: 3600
    })
    res.send({
        flag: true,
        message: "获取成功",
        data: {
            token
        }
    })
})
// 账号密码登录
app.get('/login', (req, res) => {
    let { username, password } = req.query;
    connection.query(`select * from user where username='${username}'`, (err, result) => {
        if (err) {
            console.log(err, new Date());
            res.send({ flag: false, message: "系统出错" }
            )
            return
        }

        if (result.length == 0) {
            res.send({
                flag: false,
                message: "用户名不存在",
                data: null
            })
            return
        }
        // console.log(result)
        if (result[0].password == password) {
            let playLoad = { username, password };
            // sign签名
            let token = jwt.sign(playLoad, SECRET, {
                // expiresIn: '7 days'
                expiresIn: '2 h'
            })
            res.setHeader('user-id', result[0].id);
            res.setHeader('token', token);
            res.send({
                flag: true,
                message: "登录成功",
                data: { token, ...result[0] }
            })
        } else {
            res.send({
                flag: false,
                message: "密码错误",
                data: null
            })
        }

    })

})
// 微信登陆--register
app.get('/wxLogin', (req, res) => {
    const { code, appid } = req.query || {};
    axios.get('https://api.weixin.qq.com/sns/jscode2session?js_code=' + code, {
        params: {
            appid: 'wxf5fe39bd5e979ef9',
            js_code: code,
            grant_type: 'authorization_code',
            secret: 'e16a25000b5c165c84d03c38dba2e4e7'
        }
    }
    ).then((wxData) => {
        const { data } = wxData || {};
        const { session_key, openid } = data;
        connection.query(`select openid from wx_user where openid='${openid}'`, (err, results) => {
            if (err) {
                console.log(err, new Date());
                return res.send({ flag: false, message: "系统出错" })

            }
            // console.log(results, 'results', openid, session_key)
            // exist
            if (results.length == 1) {
                connection.query(`update wx_user set session_key='${session_key}' where openid='${openid}'`, (err) => {
                    if (err) {
                        console.log(err, new Date());
                        return res.send({ flag: false, message: "系统出错" })
                    }
                    connection.query(`select * from user where username='${openid}'`, (err, usertable) => {
                        if (err) {
                            console.log(err, new Date());
                            return res.send({ flag: false, message: "系统出错" })
                        }
                        let playLoad = { username:openid, password:openid.slice(0,6) };
                        // sign签名
                        let token = jwt.sign(playLoad, SECRET, {
                            // expiresIn: '7 days'
                            expiresIn: '2 h'
                        })
                        return res.send({
                            flag: true,
                            message: "登录成功",
                            data: {...usertable[0],token}
                        })
                    })
                })

            } else {
                // register
                connection.query(`insert into wx_user(openid,session_key) values("${openid}","${session_key}")`, (err) => {
                    if (err) {
                        console.log(err, new Date());
                        return res.send({ flag: false, message: "系统出错" })
                    }
                    let name = randomNum(1, 100);
                    connection.query(`insert into user(username,password,name,avator,sex) values("${openid}","${openid.slice(0, 6)}","微信用户${name}","/default.jpg",-1)`, (err, insertData) => {
                        if (err) {
                            console.log(err, new Date());
                            res.send({ flag: false, message: "系统出错" }
                            )
                            return
                        }
                        console.log('user table', insertData)
                        let playLoad = { username:openid, password:openid.slice(0,6) };
                        // sign签名
                        let token = jwt.sign(playLoad, SECRET, {
                            // expiresIn: '7 days'
                            expiresIn: '2 h'
                        })
                        return res.send({
                            flag: true,
                            message: "登录成功",
                            data: {
                                name: '微信用户' + name,
                                username: openid,
                                password: openid.slice(0, 6),
                                avator: '/default.jpg',
                                id: insertData.insertId,
                                sex: -1,
                                token
                            }
                        })
                    })

                })
            }
        })

    }).catch(() => {
        console.log('catch====================>>>>>>>')
        return res.send({
            flag: false,
            message: '登录失败'
        })
    })
})
app.get('/mgr/login', (req, res) => {
    let { password } = req.query;
    connection.query(`select password from admin where username='admin'`, (err, result) => {
        if (err) {
            res.send({ flag: false, message: "系统出错" }
            )
        }
        if (result[0].password == password) {
            res.send({
                flag: true,
                message: "登录成功",
                data: {
                    userInfo: 'admin'
                }
            })
        } else {
            res.send({
                flag: false,
                message: "密码错误",
                data: null
            })
        }

    })

})

// 注册
app.get('/register', (req, res) => {
    let { username, password } = req.query;
    if (!username || !username) {
        return res.send({
            flag: false,
            message: "违法输入"
        })
    }
    if (username.length < 3 || username.length > 10) {
        return res.send({
            flag: false,
            message: "用户名长度为3到10位"
        })
    }
    connection.query(`select username from user where username="${username}"`, (err, results) => {
        if (err) {
            console.log(err, new Date());
            res.send({ flag: false, message: "系统出错" }
            )
            return
        }
        if (results.length == 1) {
            res.send({
                flag: false,
                message: "用户名已存在",
                data: null
            })
            return
        }
        connection.query(`insert into user(username,password,name,avator,sex) values("${username}","${password}","新用户${randomNum(1, 100000)}","/default.jpg",-1)`, (err) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }
            res.json({
                flag: true,
                message: "注册成功",
                data: [
                    {
                        username,
                        password
                    }
                ]
            })
        })
    })
})

app.get('/modyfyname', (req, res) => {
    const { name } = req.query;
    const { 'user-id': id } = req.headers;
    userExist(id, res, false, req).then(() => {
        connection.query(`update user set name='${name}' where id=${id}`, (err, /* result */) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }

            connection.query(`update message set name='${name}' where userId=${id}`, (err) => {
                if (err) {
                    console.log(err, new Date());
                    res.send({ flag: false, message: "系统出错" }
                    )
                    return
                }
                res.send({
                    data: { name },
                    flag: true,
                    message: "ok"
                })
            })
        })
    }).catch(() => { })
})

// 修改密码
app.get('/modifyPwd', (req, res) => {
    const { password } = req.query;
    const { 'user-id': userId } = req.headers;
    userExist(userId, res, false, req).then(() => {
        connection.query(`update user set password='${password}' where id=${userId} `, (err, result) => {
            if (err) {
                return res.send({
                    flag: false,
                    message: "系统错误"
                })
            }
            res.send({
                flag: true,
                code: 'modifyPwd',
                message: "修改密码成功,请重新登录,密码为" + password,
                data: result
            })
        })
    }).catch(() => { })

})

// 接收文件,更新头像
app.post('/uploadImg', (req, res) => {
    // let form = new formidable.IncomingForm();
    const { 'user-id': id } = req.headers;
    userExist(id, res, false, req).then(() => {
        let form = new formidable.IncomingForm();
        form.uploadDir = path.join(process.cwd(), '/upload')

        let arrFile = []
        form.on('file', (...args) => {
            arrFile.push(args[1])
        })

        form.parse(req, (err) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }
            let promiseList = arrFile.map((files) => {
                // 定义文件名
                return new Promise((resolve, reject) => {
                    let filepath = files.filepath;
                    let filename = files.originalFilename;
                    let extname = path.extname(filename)
                    let newFilename = files.newFilename + extname;
                    // 重命名文件
                    fs.rename(filepath, path.join(process.cwd() + '/upload/' + newFilename), (err) => {
                        if (err) {
                            reject()
                        }
                        resolve(newFilename)
                    })
                })
            })
            Promise.all(promiseList).then((data) => {
                let result = (data || []).map((item) => {
                    return new Promise((resolve, reject) => {
                        // 插入用户数据
                        connection.query(`update user set avator="/${item}" where id=${id}`,
                            (err/* , results */) => {
                                if (err) {
                                    reject(err);
                                }

                                // 更新所有自己消息的头像
                                connection.query(`update message set avator="/${item}" where userId=${id}`, (err) => {
                                    if (err) {
                                        console.log(err, new Date());
                                        res.send({ flag: false, message: "系统出错" }
                                        )
                                        return
                                    }
                                    resolve({
                                        avator: "/" + item,
                                    })
                                })

                            })
                    })
                })

                Promise.all(result).then((dataBase) => {
                    res.send({
                        data: dataBase,
                        message: "上传成功",
                        code: 1
                    })
                }).catch((/* err */) => {
                    res.send({
                        message: '上传失败',
                        code: 0,
                        data: null
                    })
                })

            }).catch(() => {
                res.send({
                    message: '上传失败',
                    code: 0,
                    data: null
                })
            })

            // // 定义文件名
            // let filename = files.file.originalFilename;
            // // 重命名文件
            // fs.rename(files.file.filepath, path.join(process.cwd() + '/upload/' + filename), (err) => {
            //     if (err) {
            //         return res.send({
            //             message: '上传失败',
            //             flag: false,
            //         })
            //     }
            //     res.send({
            //         msg: '上传成功',
            //         data: filename,
            //         code: 1
            //     })
            // })
        })
    }).catch(() => { })
})

// 判断用户是否存在（客户端）
function userExist(userId, res, type, req) {
    userId = Number(userId)
    if (!type) {
        return new Promise((resolve, reject) => {
            jwt.verify(req.headers.token, SECRET, (TokenErr, decode) => {
                if (TokenErr) {
                    res.send({
                        flag: false,
                        code: -1,
                        data: null,
                        message: "登录已过期请重新登录"
                    })
                    reject();
                    return
                }
                connection.query(`select * from user where id=${userId}`, (err, result) => {
                    if (err) {
                        console.log(err, new Date());
                        res.send({ flag: false, message: "系统出错" }
                        )
                        return
                    }
                    if (result.length == 0) {
                        res.send({
                            flag: false,
                            code: -1,
                            data: null,
                            message: "当前用户不存在,请重新登录。"
                        })
                        reject();
                        return
                    }
                    resolve();
                })
            });
        })
    }
    // websocket
    else {
        return new Promise((resolve, reject) => {
            // websocket通过query获取token
            const { token } = req.query || {};
            jwt.verify(token, SECRET, (TokenErr, decode) => {
                if (TokenErr) {
                    res.send(JSON.stringify({
                        isExitsUser: true,
                        message: "登录已过期请重新登录"
                    }))
                    return
                }
                connection.query(`select * from user where id=${userId}`, (err, result) => {
                    if (err) {
                        res.send(JSON.stringify({
                            isExitsUser: true,
                            message: "系统出错"
                        }))
                        return
                    }
                    if (result.length == 0) {
                        res.send(JSON.stringify({
                            isExitsUser: true,
                            message: "当前用户不存在,请重新登录。"
                        }))
                        reject();
                        return
                    }
                    resolve();

                })
            });

        })
    }



}

// online
app.get('/getOnlinePerson', (req, res) => {
    const { 'user-id': id } = req.headers;
    userExist(id, res, false, req).then(() => {
        res.send({
            flag: true,
            data: {
                onlinePerson: getOnlinePerson()
            },
            message: "获取成功"
        })
    }).catch(() => { })
})

// 获取所有消息
app.get('/messageList', (req, res) => {
    const { 'user-id': id } = req.headers;
    userExist(id, res, false, req).then(() => {
        connection.query(`select * from message`, (err, result) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }
            // console.log(result)
            result['onlinePerson'] = getOnlinePerson();
            res.send({
                flag: true,
                data: result,
                message: "获取成功"
            })
        })
    }).catch(() => { })
    // connection.query(`select * from user where id=${id}`, (err, result) => {
    //     if (err) {
    //         console.log(err, new Date());
    //         res.send({ flag: false, message: "系统出错" }
    //         )
    //         return
    //     }
    //     if (result.length == 0) {
    //         res.send({
    //             flag: false,
    //             code: -1,
    //             data: null,
    //             message: "用户不存在"
    //         })
    //         return
    //     }
    //     connection.query(`select * from message  limit 100`, (err, result) => {
    //         if (err) {
    //             console.log(err, new Date());
    //             res.send({ flag: false, message: "系统出错" }
    //             )
    //             return
    //         }
    //         // console.log(result)
    //         res.send({
    //             flag: true,
    //             data: result,
    //             message: "获取成功"
    //         })
    //     })
    // })
})
// 获取所有消息 -后台
app.get('/mgr/messageList', (req, res) => {
    connection.query(`select * from admin where username='admin'`, (err, result) => {
        if (err) {
            console.log(err, new Date());
            res.send({ flag: false, message: "系统出错" }
            )
            return
        }
        if (result.length == 0) {
            res.send({
                flag: false,
                data: null,
                message: "用户不存在"
            })
            return
        }

        connection.query(`select * from message`, (err, result) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }
            res.send({
                flag: true,
                data: result,
                message: "获取成功"
            })
        })
    })
})

// 获取所有用户
app.get('/mgr/userList', (req, res) => {
    connection.query(`select * from admin where username='admin'`, (err, result) => {
        if (err) {
            console.log(err, new Date());
            res.send({ flag: false, message: "系统出错" }
            )
            return
        }
        if (result.length == 0) {
            res.send({
                flag: false,
                data: null,
                message: "用户不存在"
            })
            return
        }
        connection.query(`select * from user`, (err, result) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }
            res.send({
                flag: true,
                data: result,
                message: "获取成功"
            })
        })
    })
})

// 删除消息
app.delete('/delete/message', (req, res) => {
    let { ids } = req.query;
    if (!ids) {
        ids = req.body.ids
    }
    ids = ids.split(',')
    let result_ps = ids.map((id) => {
        id = Number(id);
        return new Promise((resolve, reject) => {
            connection.query(`select * from message where id=${id}`, (err, result) => {
                if (err) {
                    console.log(err, new Date());
                    res.send({ flag: false, message: "系统出错" }
                    )
                    return
                }
                if (result.length == 0) {
                    reject();
                }
                // console.log(result)
                resolve(result[0])
            })
        })
    })


    Promise.all(result_ps).then((data) => {
        let ps = data.map((item) => {
            return new Promise((resolve/* , reject */) => {
                connection.query(`delete from message where id=${item.id}`, (err) => {
                    if (err) {
                        console.log(err, new Date());
                        res.send({ flag: false, message: "系统出错" }
                        )
                        return
                    }
                    resolve()
                })
            })
        })

        Promise.all(ps).then(() => {
            res.send({
                data: data,
                message: "删除成功",
                flag: true
            })
        }).catch(() => {
            res.send({
                data: null,
                message: "删除失败",
                flag: false
            })
        })


    }).catch(() => {
        res.send({
            data: null,
            message: "删除失败",
            flag: false
        })
    })
})
// 删除用户
app.delete('/delete/user', (req, res) => {
    let { ids } = req.query;
    if (!ids) {
        ids = req.body.ids
    }
    ids = ids.split(',')
    let result_ps = ids.map((id) => {
        id = Number(id);
        return new Promise((resolve, reject) => {
            connection.query(`select * from user where id=${id}`, (err, result) => {
                if (err) {
                    console.log(err, new Date());
                    res.send({ flag: false, message: "系统出错" }
                    )
                    return
                }
                if (result.length == 0) {
                    reject();
                }
                // console.log(result)
                resolve(result[0])
            })
        })
    })


    Promise.all(result_ps).then((data) => {
        let ps = data.map((item) => {
            return new Promise((resolve/* , reject */) => {
                connection.query(`delete from user where id=${item.id}`, (err) => {
                    if (err) {
                        console.log(err, new Date());
                        res.send({ flag: false, message: "系统出错" }
                        )
                        return
                    }
                    resolve()
                })
            })
        })

        Promise.all(ps).then(() => {
            res.send({
                data: data,
                message: "删除成功",
                flag: true
            })
        }).catch(() => {
            res.send({
                data: null,
                message: "删除失败",
                flag: false
            })
        })


    }).catch(() => {
        res.send({
            data: null,
            message: "删除失败",
            flag: false
        })
    })
})

// 接收文件，发送图片
app.post('/sendImg', (req, res) => {
    // let form = new formidable.IncomingForm();
    const { 'user-id': userId } = req.headers;
    userExist(userId, res, false, req).then(() => {
        let form = new formidable.IncomingForm();
        form.uploadDir = path.join(process.cwd(), '/upload')

        let arrFile = []
        form.on('file', (...args) => {
            arrFile.push(args[1])
        })


        form.parse(req, (err, fields) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }
            // 获取文件传参
            const { time, name, avator } = fields;
            if (!time || !time || !avator) {
                return res.send({
                    flag: false,
                    message: "参数不能为空"
                })
            }
            let promiseList = arrFile.map((files) => {
                // 定义文件名
                return new Promise((resolve, reject) => {
                    let filepath = files.filepath;
                    let filename = files.originalFilename;
                    let extname = path.extname(filename);
                    let newFilename = files.newFilename + extname;
                    // 重命名文件
                    fs.rename(filepath, path.join(process.cwd() + '/upload/' + newFilename), (err) => {
                        if (err) {
                            reject()
                        }
                        resolve(newFilename)
                    })
                })
            })

            Promise.all(promiseList).then((data) => {
                let result = (data || []).map((item) => {
                    return new Promise((resolve) => {
                        let timestamp = new Date().getTime();
                        connection.query(`insert into message(userId,message,avator,name,time,timestamp,type) values("${userId}","/${item}","${avator}","${name}","${time}","${timestamp}","img")`, (err, result) => {
                            if (err) {
                                console.log(err, new Date());
                                res.send({ flag: false, message: "系统出错" }
                                )
                                return
                            }
                            // 向所有客户端发送消息
                            let onlinePerson = getOnlinePerson();
                            resolve({
                                onlinePerson,
                                userId,
                                name,
                                avator,
                                time,
                                message: "/" + item,
                                timestamp,
                                id: result.insertId,
                                type: "img"
                            });
                        })
                    })
                })

                Promise.all(result).then((dataBase) => {
                    dataBase.forEach((item) => {
                        wss.clients.forEach((e) => {
                            e.send(JSON.stringify(item))
                        })
                    })
                    res.send({
                        data: dataBase,
                        message: "发送成功",
                        code: 1,
                        flag: true,
                    })
                }).catch((/* err */) => {
                    res.send({
                        message: '发送失败',
                        code: 0,
                        data: null,
                        flag: false,
                    })
                })

            }).catch(() => {
                res.send({
                    message: '发送失败',
                    code: 0,
                    data: null,
                    flag: false,
                })
            })

        })
    }).catch(() => { })
    // const { time, name, avator } = req.body;
    // req.on('data', (data) => {
    //     const { time, name, avator } = JSON.stringify(data);
    //     console.log(time, name, avator)
    // })


})


// 发送消息
// 获取所有客户端
const wss = WSS.getWss();
const getOnlinePerson = function () {
    let onlinePerson = '';
    let userIds = [];
    wss.clients.forEach((e) => {
        // console.log(e._protocol, typeof e.protocol)
        userIds.push(e._protocol)
    })
    onlinePerson = {
        num: [...new Set(userIds)].length,
        userIds: [...new Set(userIds)]
    };
    return onlinePerson
}

app.ws('/connect', (ws, req) => {
    // console.log(req.headers['sec-websocket-protocol'])
    // vue-cli
    let userId = Number(req.headers['sec-websocket-protocol'])
    // uni-app
    if (!userId) {
        userId = Number(req.headers['user-id']);
    }
    // 返回给客户端
    // 监听 message 事件，拿到客户端通过 websocket 发送过来的数据
    ws.on('message', (msg) => {
        // 业务代码
        userExist(userId, ws, 'websocket', req).then(() => {
            const { message, avator, name, time, type } = JSON.parse(msg);
            let timestamp = new Date().getTime();
            let onlinePerson = getOnlinePerson();
            if (type == 'img') {
                connection.query(`insert into message(userId,message,avator,name,time,timestamp,type) values("${userId}","${message}","${avator}","${name}","${time}","${timestamp}","img")`, (err, result) => {
                    if (err) {
                        console.log(err, new Date());

                        return
                    }
                    // 向所有客户端发送消息
                    wss.clients.forEach((e) => {
                        e.send(JSON.stringify({
                            onlinePerson,
                            userId,
                            name,
                            avator,
                            time,
                            message,
                            timestamp,
                            id: result.insertId,
                            type: 'img'
                        }))
                    })
                })
                return
            }
            connection.query(`insert into message(userId,message,avator,name,time,timestamp,type) values("${userId}","${message}","${avator}","${name}","${time}","${timestamp}","text")`, (err, result) => {
                if (err) {
                    console.log(err, new Date());

                    return
                }
                // 向所有客户端发送消息
                wss.clients.forEach((e) => {
                    e.send(JSON.stringify({
                        onlinePerson,
                        userId,
                        name,
                        avator,
                        time,
                        message,
                        timestamp,
                        id: result.insertId,
                        type: 'text'
                    }))
                })
            })
        }).catch(() => { })
    })
})

// 撤销消息
app.get('/backMessage', (req, res) => {
    const { id, currentTime } = req.query;
    let userId = Number(req.headers['user-id']);
    userExist(userId, res, false, req).then(() => {
        connection.query(`select * from message where id=${id}`, (err, result) => {
            if (err) {
                console.log(err, new Date());
                res.send({ flag: false, message: "系统出错" }
                )
                return
            }
            if (result.length == 0) {
                res.send({
                    flag: false,
                    message: "消息已撤回"
                })
                return
            }

            let val = currentTime - result[0].timestamp;
            // 2分钟 120s
            if (val <= 120 * 1000) {
                connection.query(`delete from message where id=${id}`, (err) => {
                    if (err) {
                        console.log(err, new Date());
                        res.send({ flag: false, message: "系统出错" }
                        )
                        return
                    }
                    res.send({
                        flag: true,
                        message: "消息已撤回",
                        data: result[0]
                    })
                    let onlinePerson = getOnlinePerson();
                    wss.clients.forEach((e) => {
                        e.send(JSON.stringify({ type: "backMessage", result: result[0], onlinePerson }))
                    })
                })
            } else {
                res.send({
                    flag: false,
                    message: "超过2分钟时间无法撤回"
                })
            }
        })
    }).catch(() => { })
})

// 修改用户信息
app.post('/modifyUserInfo', (req, res) => {
    console.log(req.body)
    const { 'user-id': id } = req.headers;
    const { name, age, sex, sign, password } = req.body || {};
    userExist(id, res, false, req).then(() => {
        const sql = `update user set name='${name}',age='${age}',sex='${sex}',sign='${sign}'${password ? ',password=' + password : ''} where id=${id}`;
        // connection.query(`update user set name='${name}' where id=${id}`, (err, /* result */) => {
        connection.query(sql, (err, result) => {
            if (err) {
                return res.send({
                    flag: false,
                    message: "系统错误"
                })
            }
            // 更新所有自己消息的头像
            connection.query(`update message set name="${name}" where userId=${id}`, (err) => {
                if (err) {
                    console.log(err, new Date());
                    res.send({ flag: false, message: "系统出错" }
                    )
                    return
                }
                res.send({
                    flag: true,
                    message: "修改成功",
                    data: {
                        name, age, sex, sign, result, password
                    }
                })
            })

        })
    }).catch(() => { })

})
// 获取用户信息
app.get('/getUserInfo', (req, res) => {
    const { userId: id } = req.query;
    const { 'user-id': userid } = req.headers;
    userExist(userid, res, false, req).then(() => {
        connection.query(`select name,username,avator,age,sex,sign,id from user where id=${id}`, (err, result) => {
            if (err) return res.send({
                flag: false,
                message: "系统出错"
            })
            res.send({
                flag: true,
                message: "查询成功",
                data: result[0]
            })
        })
    }).catch(() => { })

})

// 获取视频日志
app.get('/getVideoLog', (req, res) => {
    const { 'user-id': userId } = req.headers || {};
    const sql = userId ? `select * from video_log where userId=${userId}` : `select * from video_log`;
    connection.query(sql, (err, result) => {
        if (err) {
            console.log(err, new Date());
            return res.send({ flag: false, message: "系统出错" })
        }

        res.send({
            flag: true,
            message: "ok",
            data: result
        })
    })
})

app.post('/addVideoLog', (req, res) => {
    const { name, time, type, avator, content } = req.body || {};
    const { 'user-id': userId } = req.headers || {};
    if (!name || !userId || !avator) {
        return res.send({
            flag: false,
            message: "请传参正确",
            data: { name, userId, time, type, avator, content }
        })
    }
    connection.query(`insert into video_log(name,time,type,avator,content,userId) values("${name}","${time}","${type}","${avator}","${content}",${userId})`, (err, result) => {
        if (err) {
            console.log(err, new Date());
            return res.send({ flag: false, message: "系统出错" })
        }
        res.send({
            flag: true,
            message: "ok",
            data: result
        })
    })
})
//为了获取到所以的客户端

// 生成随机整数数
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);

        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);

        default:
            return 0;

    }
}
/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
    var ifaces = os.networkInterfaces()
    for (var dev in ifaces) {
        let iface = ifaces[dev]
        for (let i = 0; i < iface.length; i++) {
            let { family, address, internal } = iface[i]
            if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
                return address
            }
        }
    }
}